
package com.tsh.core.tenant.dynamic;

import com.tsh.core.tenant.exception.TenantDataSourceException;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.Setter;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import com.tsh.core.secure.utils.AuthUtil;
import com.tsh.core.tool.utils.StringUtil;

/**
 * 租户数据源全局拦截器
 *
 * @author Tsh
 */
public class TenantDataSourceGlobalInterceptor implements MethodInterceptor {

	@Setter
	private TenantDataSourceHolder holder;

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		String tenantId = AuthUtil.getTenantId();
		try {
			if (StringUtil.isNotBlank(tenantId)) {
				holder.handleDataSource(tenantId);
				DynamicDataSourceContextHolder.push(tenantId);
			}
			return invocation.proceed();
		} catch (Exception exception) {
			throw new TenantDataSourceException(exception.getMessage());
		} finally {
			if (StringUtil.isNotBlank(tenantId)) {
				DynamicDataSourceContextHolder.poll();
			}
		}
	}
}
